package com.ynwa.guava;

import com.google.common.util.concurrent.*;

import javax.annotation.Nullable;
import java.util.concurrent.*;

/**
 * @author gzd
 * @date 2020-05-03 22:18
 */
public class FutureTest {

    /**
     * 最简单的例子
     *
     * @throws ExecutionException
     * @throws InterruptedException
     */
    private static ListeningExecutorService simplestCase() throws Exception {
        ListeningExecutorService executorService = producePool();
        SettableFuture<String> settableFuture = SettableFuture.create();
        Futures.addCallback(settableFuture, new FutureCallback<String>() {
            @Override
            public void onSuccess(@Nullable String result) {
                settableFuture.set(result);
            }

            @Override
            public void onFailure(Throwable t) {
                settableFuture.set("异常了.." + t.toString());
            }

        }, executorService);

        ListenableFuture<String> submit = executorService.submit(produceCallable(10));

        System.out.println(submit.get(5, TimeUnit.SECONDS));
        return executorService;
    }


    private static Callable<String> produceCallable() {
        return produceCallable(0);
    }

    private static Callable<String> produceCallable(int sleepSeconds) {
        return () -> {
            if (sleepSeconds > 0) {
                TimeUnit.SECONDS.sleep(sleepSeconds);
            }
            return "我是线程: " + Thread.currentThread().getName();
        };
    }


    private static ListeningExecutorService producePool() {
        // 装饰器模式, 将传入的ExecutorService, 装饰成ListeningExecutorService
        return MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(5));
    }


    public static void main(String[] args) throws Exception {
        ListeningExecutorService listeningExecutorService = simplestCase();
        listeningExecutorService.shutdown();
    }
}
